import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  message, 
  Card, 
  Tag, 
  Space, 
  Tabs, 
  Row, 
  Col,
  Switch,
  Typography,
  Divider,
  Tooltip
} from 'antd';
import { 
  EditOutlined, 
  PlusOutlined, 
  SyncOutlined, 
  FolderOutlined,
  SettingOutlined,
  SaveOutlined,
  EyeOutlined,
  DeleteOutlined,
  DatabaseOutlined,
  CloudSyncOutlined,
  CloudUploadOutlined
} from '@ant-design/icons';
import OperationNavBar from '../components/OperationNavBar';
import { 
  getAllSysConf, 
  updateSysConf, 
  deleteSysConf,
  validatePath, 
  getConfigTypeTag,
  type DirectoryConfig, 
  type SystemConfig 
} from '../api/directoryManagement';
import './DirectoryManagement.css';

const { Title, Text } = Typography;
const { TabPane } = Tabs;

interface ConfigItem extends DirectoryConfig {
  key: string;
  category: string;
}

const DirectoryManagement: React.FC = () => {
  const [systemConfig, setSystemConfig] = useState<SystemConfig>({});
  const [loading, setLoading] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [viewModalVisible, setViewModalVisible] = useState(false);
  const [currentConfig, setCurrentConfig] = useState<ConfigItem | null>(null);
  const [form] = Form.useForm();
  const [activeTab, setActiveTab] = useState('ROLL');

  // 获取系统配置
  const fetchSystemConfig = async () => {
    setLoading(true);
    try {
      const response = await getAllSysConf();
      if (response.success && response.data) {
        setSystemConfig(response.data);
      } else {
        // 如果接口失败，使用模拟数据
        const mockConfig: SystemConfig = {
          ROLL: {
            TW2: {
              PATH: '/TW2ROLL',
              HISTORY: '/TW2ROLL',
              NAME: '天问二号归档数据存储目录'
            },
            TW1: {
              PATH: '/HX1ROLL',
              HISTORY: '/HX1ROLL',
              NAME: '天问一号归档数据存储目录'
            },
            CE1: {
              PATH: '/CE1ROLL',
              HISTORY: '/CE1ROLL',
              NAME: '嫦娥一号归档数据存储目录'
            },
            CE2: {
              PATH: '/CE2ROLL',
              HISTORY: '/CE2ROLL',
              NAME: '嫦娥二号归档数据存储目录'
            }
          },
          SYNC: {
            TW: {
              PATH: '/PLANETARY-DATA',
              NAME: '天问系列同步根路径',
              ISMON: 0
            },
            CE: {
              PATH: '/LUNAR-DATA',
              NAME: '嫦娥系列同步根路径',
              ISMON: 0
            },
            FTP: {
              PATH: '/FTPUSER',
              NAME: '订单文件同步根路径',
              ISMON: 1
            }
          },
          PUB: {
            TW2: {
              PATH: '/PUBDATA/TW2ROLL',
              NAME: '天问二号数据发布同步路径',
              USER: 'NEITOWAI',
              PWD: 'neitowai',
              IP: '191.168.25.111'
            }
          }
        };
        setSystemConfig(mockConfig);
        message.warning('使用模拟数据，请检查网络连接');
      }
    } catch (error) {
      message.error('获取配置失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSystemConfig();
  }, []);

  // 将配置转换为表格数据
  const getTableData = (category: string): ConfigItem[] => {
    const categoryConfig = systemConfig[category as keyof SystemConfig];
    if (!categoryConfig) return [];
    
    return Object.entries(categoryConfig).map(([key, config]) => ({
      key,
      category,
      ...config
    }));
  };

  // 编辑配置项
  const handleEdit = (record: ConfigItem) => {
    setCurrentConfig(record);
    form.setFieldsValue({
      key: record.key,
      PATH: record.PATH,
      NAME: record.NAME,
      HISTORY: record.HISTORY || '',
      ISMON: record.ISMON || 0,
      USER: record.USER || '',
      PWD: record.PWD || '',
      IP: record.IP || ''
    });
    setEditModalVisible(true);
  };

  // 查看配置项详情
  const handleView = (record: ConfigItem) => {
    setCurrentConfig(record);
    setViewModalVisible(true);
  };

  // 保存配置
  const handleSave = async (values: any) => {
    if (!currentConfig) return;

    try {
      // 验证路径格式
      if (!validatePath(values.PATH)) {
        message.error('路径格式不正确，应以/开头，只包含字母、数字、-、_、/');
        return;
      }

      // 构建更新配置
      const updateConfig = {
        L1: currentConfig.category,
        L2: {
          [values.key]: {
            PATH: values.PATH,
            NAME: values.NAME,
            ...(values.HISTORY && { HISTORY: values.HISTORY }),
            ...(currentConfig.category === 'SYNC' && { ISMON: values.ISMON }),
            ...(currentConfig.category === 'PUB' && values.USER && { USER: values.USER }),
            ...(currentConfig.category === 'PUB' && values.PWD && { PWD: values.PWD }),
            ...(currentConfig.category === 'PUB' && values.IP && { IP: values.IP })
          }
        }
      };

      const response = await updateSysConf(updateConfig);
      if (response.success) {
        message.success('配置更新成功');
        setEditModalVisible(false);
        form.resetFields();
        fetchSystemConfig();
      } else {
        message.error(response.message || '更新失败');
      }
    } catch (error) {
      message.error('保存配置失败');
    }
  };

  // 添加新配置项
  const handleAdd = () => {
    setCurrentConfig({ 
      key: '', 
      category: activeTab, 
      PATH: '', 
      NAME: '' 
    } as ConfigItem);
    form.resetFields();
    form.setFieldsValue({ key: '', PATH: '', NAME: '', HISTORY: '', ISMON: 0 });
    setEditModalVisible(true);
  };

  // 删除配置项
  const handleDelete = (record: ConfigItem) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除配置项 "${record.key}" 吗？此操作不可恢复。`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await deleteSysConf({
            L1: record.category,
            L2: record.key
          });
          
          if (response.success) {
            message.success('删除成功');
            fetchSystemConfig(); // 刷新数据
          } else {
            message.error(response.message || '删除失败');
          }
        } catch (error) {
          message.error('删除操作失败');
        }
      }
    });
  };

  // 表格列配置
  const getColumns = (category: string) => {
    const baseColumns = [
      {
        title: '配置项',
        dataIndex: 'key',
        key: 'key',
        width: 180,
        render: (text: string) => (
          <Tag color="blue" icon={<FolderOutlined />}>
            {text}
          </Tag>
        )
      },
      {
        title: '名称',
        dataIndex: 'NAME',
        key: 'NAME',
        ellipsis: { showTitle: false },
        render: (text: string) => (
          <Tooltip title={text}>
            <Text>{text}</Text>
          </Tooltip>
        )
      },
      {
        title: '路径',
        dataIndex: 'PATH',
        key: 'PATH',
        ellipsis: { showTitle: false },
        render: (text: string) => (
          <Tooltip title={text}>
            <Text code>{text}</Text>
          </Tooltip>
        )
      }
    ];

    const additionalColumns = [];

    if (category === 'ROLL') {
      additionalColumns.push({
        title: '历史路径',
        dataIndex: 'HISTORY',
        key: 'HISTORY',
        ellipsis: { showTitle: false },
        render: (text: string) => (
          <Tooltip title={text}>
            <Text code>{text || '-'}</Text>
          </Tooltip>
        )
      });
    }

    if (category === 'SYNC') {
      additionalColumns.push({
        title: '监控状态',
        dataIndex: 'ISMON',
        key: 'ISMON',
        width: 100,
        render: (ismon: number) => (
          <Tag color={ismon === 1 ? 'green' : 'default'}>
            {ismon === 1 ? '监控中' : '未监控'}
          </Tag>
        )
      });
    }

    if (category === 'PUB') {
      additionalColumns.push(
        {
          title: '用户名',
          dataIndex: 'USER',
          key: 'USER',
          width: 100,
          render: (text: string) => text || '-'
        },
        {
          title: 'IP地址',
          dataIndex: 'IP',
          key: 'IP',
          width: 140,
          render: (text: string) => (
            <Text code>{text || '-'}</Text>
          )
        }
      );
    }

    const actionColumn = {
      title: '操作',
      key: 'action',
      width: 160,
      render: (record: ConfigItem) => (
        <Space>
          <Button 
            type="primary" 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            danger 
            size="small" 
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      )
    };

    return [...baseColumns, ...additionalColumns, actionColumn];
  };

  return (
    <div className="directory-management-container">
      {/* 运行管理导航条 */}
      <OperationNavBar />

      <Card className="directory-management-card">
        <div className="directory-management-header">
          <div className="title-section">
            <Title level={4}>
              <SettingOutlined /> 业务目录管理
            </Title>
            <Text type="secondary">
              &emsp;&emsp;<Text strong>归档目录配置：</Text>各型号任务进行探测数据归档时的数据存储根路径。所有任务历史路径用于异常数据检测文件系统检测。<br />
              &emsp;&emsp;<Text strong>业务目录配置：</Text>数据同步、数据交换、订单下载、PDS数据集生成、GIS数据等业务执行时的工作路径，并可指定需要进行磁盘空间监视及清理的目录。<br />
              &emsp;&emsp;<Text strong>发布配置：</Text>将数据从内网推送到外网进行数据发布时的配置参数，包括数据发布服务器、用户、密码、端口及数据推送目录等。
            </Text>
          </div>
          <div className="action-section">
            <Space>
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                新增配置
              </Button>
              <Button 
                icon={<SyncOutlined />} 
                onClick={fetchSystemConfig}
                loading={loading}
              >
                刷新
              </Button>
            </Space>
          </div>
        </div>

        <Divider />

        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane 
            tab={
              <span>
                <DatabaseOutlined style={{ color: '#1890ff', marginRight: 8 }} />
                归档数据存储配置
              </span>
            } 
            key="ROLL"
          >
            <Table
              columns={getColumns('ROLL')}
              dataSource={getTableData('ROLL')}
              rowKey="key"
              loading={loading}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                pageSizeOptions: ['5', '10', '20', '50'],
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                showQuickJumper: true,
                size: 'small'
              }}
              size="small"
              bordered
              rowClassName={(_, index) => index % 2 === 0 ? 'table-row-even' : 'table-row-odd'}
            />
          </TabPane>

          <TabPane 
            tab={
              <span>
                <CloudSyncOutlined style={{ color: '#52c41a', marginRight: 8 }} />
                数据同步配置
              </span>
            } 
            key="SYNC"
          >
            <Table
              columns={getColumns('SYNC')}
              dataSource={getTableData('SYNC')}
              rowKey="key"
              loading={loading}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                pageSizeOptions: ['5', '10', '20', '50'],
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                showQuickJumper: true,
                size: 'small'
              }}
              size="small"
              bordered
              rowClassName={(_, index) => index % 2 === 0 ? 'table-row-even' : 'table-row-odd'}
            />
          </TabPane>

          <TabPane 
            tab={
              <span>
                <CloudUploadOutlined style={{ color: '#fa8c16', marginRight: 8 }} />
                数据发布配置
              </span>
            } 
            key="PUB"
          >
            <Table
              columns={getColumns('PUB')}
              dataSource={getTableData('PUB')}
              rowKey="key"
              loading={loading}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                pageSizeOptions: ['5', '10', '20', '50'],
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                showQuickJumper: true,
                size: 'small'
              }}
              size="small"
              bordered
              rowClassName={(_, index) => index % 2 === 0 ? 'table-row-even' : 'table-row-odd'}
            />
          </TabPane>
        </Tabs>
      </Card>

      {/* 编辑弹窗 */}
      <Modal
        title={
          <span>
            <EditOutlined /> {currentConfig?.key ? '编辑配置' : '新增配置'}
          </span>
        }
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={600}
        destroyOnHidden
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="key"
                label="配置项标识"
                rules={
                  currentConfig?.key
                    ? [{ required: true, message: '请输入配置项标识' }] // 编辑时不需要校验格式
                    : [
                        { required: true, message: '请输入配置项标识' },
                        { pattern: /^[A-Z0-9_-]+$/, message: '只能包含大写字母、数字、下划线和横杠' }
                      ]
                }
              >
                <Input 
                  placeholder="如：TW2、CE1、DATA-SYNC等" 
                  disabled={!!currentConfig?.key}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="NAME"
                label="配置名称"
                rules={[{ required: true, message: '请输入配置名称' }]}
              >
                <Input placeholder="请输入配置名称" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="PATH"
            label="目录路径"
            rules={[
              { required: true, message: '请输入目录路径' },
              { 
                validator: (_, value) => {
                  if (value && !validatePath(value)) {
                    return Promise.reject('路径格式不正确，应以/开头');
                  }
                  return Promise.resolve();
                }
              }
            ]}
          >
            <Input placeholder="请输入目录路径，如：/TW2ROLL" />
          </Form.Item>

          {currentConfig?.category === 'ROLL' && (
            <Form.Item
              name="HISTORY"
              label="历史路径"
            >
              <Input placeholder="请输入历史路径（可选）" />
            </Form.Item>
          )}

          {currentConfig?.category === 'SYNC' && (
            <Form.Item
              name="ISMON"
              label="监控状态"
              getValueFromEvent={(checked: boolean) => checked ? 1 : 0}
              getValueProps={(value: number) => ({ checked: value === 1 })}
            >
              <Switch checkedChildren="监控" unCheckedChildren="不监控" />
            </Form.Item>
          )}

          {currentConfig?.category === 'PUB' && (
            <>
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name="USER"
                    label="用户名"
                  >
                    <Input placeholder="请输入用户名" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="PWD"
                    label="密码"
                  >
                    <Input.Password placeholder="请输入密码" />
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item
                name="IP"
                label="IP地址"
                rules={[
                  { 
                    pattern: /^(\d{1,3}\.){3}\d{1,3}$/, 
                    message: '请输入正确的IP地址格式' 
                  }
                ]}
              >
                <Input placeholder="请输入IP地址" />
              </Form.Item>
            </>
          )}

          <Form.Item className="form-buttons">
            <Space>
              <Button onClick={() => setEditModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
                保存
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 查看详情弹窗 */}
      <Modal
        title={
          <span>
            <EyeOutlined /> 配置详情
          </span>
        }
        open={viewModalVisible}
        onCancel={() => setViewModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setViewModalVisible(false)}>
            关闭
          </Button>,
          <Button 
            key="edit" 
            type="primary" 
            icon={<EditOutlined />}
            onClick={() => {
              setViewModalVisible(false);
              currentConfig && handleEdit(currentConfig);
            }}
          >
            编辑
          </Button>
        ]}
        width={500}
      >
        {currentConfig && (
          <div className="config-detail">
            <Row gutter={[16, 16]}>
              <Col span={8}>
                <Text strong>配置类型：</Text>
              </Col>
              <Col span={16}>
                <Tag color={getConfigTypeTag(currentConfig.category).color}>
                  {getConfigTypeTag(currentConfig.category).text}
                </Tag>
              </Col>

              <Col span={8}>
                <Text strong>配置项：</Text>
              </Col>
              <Col span={16}>
                <Tag color="blue">{currentConfig.key}</Tag>
              </Col>

              <Col span={8}>
                <Text strong>名称：</Text>
              </Col>
              <Col span={16}>
                <Text>{currentConfig.NAME}</Text>
              </Col>

              <Col span={8}>
                <Text strong>路径：</Text>
              </Col>
              <Col span={16}>
                <Text code>{currentConfig.PATH}</Text>
              </Col>

              {currentConfig.HISTORY && (
                <>
                  <Col span={8}>
                    <Text strong>历史路径：</Text>
                  </Col>
                  <Col span={16}>
                    <Text code>{currentConfig.HISTORY}</Text>
                  </Col>
                </>
              )}

              {currentConfig.category === 'SYNC' && (
                <>
                  <Col span={8}>
                    <Text strong>监控状态：</Text>
                  </Col>
                  <Col span={16}>
                    <Tag color={currentConfig.ISMON === 1 ? 'green' : 'default'}>
                      {currentConfig.ISMON === 1 ? '监控中' : '未监控'}
                    </Tag>
                  </Col>
                </>
              )}

              {currentConfig.category === 'PUB' && (
                <>
                  {currentConfig.USER && (
                    <>
                      <Col span={8}>
                        <Text strong>用户名：</Text>
                      </Col>
                      <Col span={16}>
                        <Text>{currentConfig.USER}</Text>
                      </Col>
                    </>
                  )}
                  {currentConfig.IP && (
                    <>
                      <Col span={8}>
                        <Text strong>IP地址：</Text>
                      </Col>
                      <Col span={16}>
                        <Text code>{currentConfig.IP}</Text>
                      </Col>
                    </>
                  )}
                </>
              )}
            </Row>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default DirectoryManagement; 